const express = require('express');
const expressWs = require('express-ws')
const router = express.Router()
const wss = expressWs(router);



wss.getWss().on("connection", (ws, req)=>{
  console.log("1111uyyyy", req.query.userID)
})

expressWs.getWss().on('connection', function(ws) {
  console.log('connection open');
});
// wss.getUniqueID = function () {
//   function s4() {
//       return Math.floor((1 + Math.random()) * 0x10000).toString(16).substring(1);
//   }
//   return s4() + s4() + '-' + s4();
// };



router.ws('/test', (ws, req) => {


  console.log("dddddd", req.query.userID)
  ws.send('连接成功')

  // let interval
  // interval = setInterval(() => {
  //   if (ws.readyState === ws.OPEN) {
  //     ws.send(Math.random().toFixed(2))
  //   } else {
  //     clearInterval(interval)
  //   }
  // }, 1000)

  // ws.id = req.query.userID

  ws.on('message', msg => {
    console.log("msgmsg", msg)
    if(msg.event === 'message'){
      ws.send(msg)
    }
    if(msg.event === 'connection'){
      console.log("12123")
    }
    // console.log(wss.getWss().clients, wss.getWss().clients.size)
    // wss.getWss().clients.forEach(function each(client) {
    //   console.log('11',client.id)
    //   // if (client.readyState === WebSocket.OPEN) {  
    //   //   client.send(JSON.stringify({ message: 'Hello, all clients!' }));  
    //   // }  
    // });
    // ws.send(msg)
  })
})

module.exports = router